package com.example.day2002;

/**
 * @author Lenovo
 */
public class SelllTicket {
    public static class SellTicket implements Runnable {
        private int tickets = 100;
        private Object obj = new Object();


        public void run() {
            while (true) {
                //tickets = 100;
                //t1,t2,t3
                //假设t1抢到了CPU的执行权
                //假设t2抢到了CPU的执行权
                synchronized (obj) {
                    //t1进来后，就会把这段代码给锁起来
                    if (tickets > 0) {
                        try {
                            Thread.sleep(100);
                            //t1休息100毫秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //窗口1正在出售第100张票
                        System.out.println(Thread.currentThread().getName() + "正在出售 第" + tickets + "张票");
                                tickets--; //tickets = 99;
                    }
                }
                //t1出来了，这段代码的锁就被释放了
            }
        }
    }
    public class SellTicketDemo {
        public void main(String[] args) {
            SellTicket st = new SellTicket();
            Thread t1 = new Thread(st, "窗口1");
            Thread t2 = new Thread(st, "窗口2");
            Thread t3 = new Thread(st, "窗口3");
            t1.start();
            t2.start();
            t3.start();
        }
    }